package com.vf.admin.client.controller;

import com.vf.admin.client.common.ClientBaseController;
import com.vf.admin.client.common.ClientConstants;
import com.vf.admin.client.common.RedisKeys;
import com.vf.admin.client.dao.AppCashWithdrawalDao;
import com.vf.admin.client.dao.WithdrawFeeLevelDao;
import com.vf.admin.client.service.*;
import com.vf.admin.common.entity.Result;
import com.vf.admin.common.redis.RedisUtil;
import com.vf.admin.common.splitpage.SplitPageBean;
import com.vf.admin.miaodong.entity.AppCashWithdrawal;
import com.vf.admin.miaodong.entity.AppCashWithdrawalMoney;
import com.vf.admin.miaodong.entity.AppSetup;
import com.vf.admin.miaodong.entity.AppUser;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 提现
 */
@Controller
@RequestMapping("/app/cashwithdrawal")
public class AppCashWithdrawalController extends ClientBaseController {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    AppCashWithdrawalService appCashWithdrawalService;
    @Autowired
    AppMingxiMeilizhiService appMingxiMeilizhiService;
    @Autowired
    AppCashWithdrawalMoneyService appCashWithdrawalMoneyService;
    @Autowired
    AppSetupService appSetupService;
    @Autowired
    AppMingXiTxService appMingXiTxService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    AppUserService appUserService;
    @Autowired
    AppAuthUserService appAuthUserService;
    @Autowired
    AppCashWithdrawalDao appCashWithdrawalDao;
    @Autowired
    WithdrawFeeLevelDao withdrawFeeLevelDao;

    /**
     * 用户提交提现申请
     *
     * @param mode 1银行卡 2支付宝
     * @return
     */
    @RequestMapping("/addCash")
    @ResponseBody
    public Result addCash(Integer id, Integer mode) {
        try {
            AppSetup setup = appSetupService.get();
            if(setup.getOpenWithdraw() == 0) {
                return this.errorJSON(setup.getWithdrawTip());
            }
            if (mode == null) {
                return this.errorJSON("请选择提现方式");
            }
            Integer realNamAuth = appAuthUserService.infoByUserAndName(getUserId(), ClientConstants.UserAuth.REAL_NAME_AUTH);
            if(realNamAuth != 2) {
                return this.errorJSON("请先实名认证！");
            }
            return appCashWithdrawalService.withdraw(getUserId(), id, mode);
        } catch (Exception e) {
            logger.error("用户提交提现申请异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

    /**
     * 提现金额列表
     */
    @RequestMapping("/cashMoney")
    @ResponseBody
    public Result cashMoney() {
        try {
            Map<String, Object> map = new HashMap<>(16);
            List<AppCashWithdrawalMoney> list = appCashWithdrawalMoneyService.list();
            Integer userId = (Integer) redisUtil.get(RedisKeys.userToken + request.getHeader(ClientConstants.client_toke));
            AppUser user = appUserService.get(userId);
            map.put("list", list);
            map.put("goldCoin", user.getJinbi());
            Integer realAuth = appAuthUserService.infoByUserAndName(getUserId(), ClientConstants.UserAuth.REAL_AUTH);
            map.put("realAuth", realAuth);
            Integer realNameAuth = appAuthUserService.infoByUserAndName(getUserId(), ClientConstants.UserAuth.REAL_NAME_AUTH);
            map.put("realNameAuth", realNameAuth);

            //计算手续费
            BigDecimal withdrawedMoney = appCashWithdrawalDao.withdrawMoneySumByUserId(userId);
            BigDecimal ratio = withdrawFeeLevelDao.get(withdrawedMoney);
            map.put("ratio", ratio);
            for(AppCashWithdrawalMoney bean : list) {
                BigDecimal fee = bean.getMoney().multiply(ratio).setScale(2, BigDecimal.ROUND_HALF_UP);
                bean.setFee(fee);
                bean.setGetMoney(bean.getMoney().subtract(fee));
            }

            //转int转字符串去掉小数
            /*String jinbi = String.valueOf(user.getJinbi().intValue());
            String withdrawMoney = "0";

            //递归用数组引用传递
            List<String> data = new ArrayList<>();
            data.add(jinbi);
            data.add(withdrawMoney);
            List<AppCashWithdrawalMoney> collect = list.stream().sorted(Comparator.comparing(AppCashWithdrawalMoney::getGoldCoin).reversed()).collect(Collectors.toList());

            BigDecimal bigDecimal = BigDecimal.ZERO;
            for (AppCashWithdrawalMoney b : collect) {
                bigDecimal = new BigDecimal(addCanWithdrawMoney(b, data));
            }
            map.put("withdrawMoney", bigDecimal);*/
            return this.sucessJSON(map);
        } catch (Exception e) {
            logger.error("提现金额列表异常", e);
            return this.errorJSON("系统繁忙");
        }
    }

    public String addCanWithdrawMoney(AppCashWithdrawalMoney b, List<String> data) {
        String jinbi = data.get(0);
        String withdrawMoney = data.get(1);
        if (Integer.valueOf(jinbi).compareTo(Integer.valueOf(b.getGoldCoin().stripTrailingZeros().toPlainString())) >= 0) {
            jinbi = String.valueOf(Integer.valueOf(jinbi)-Integer.valueOf(b.getGoldCoin().stripTrailingZeros().toPlainString()));
            withdrawMoney = String.valueOf(Integer.valueOf(withdrawMoney)+Integer.valueOf(b.getMoney().stripTrailingZeros().toPlainString()));
        }
        data.clear();
        data.add(jinbi);
        data.add(withdrawMoney);
        if (Integer.valueOf(jinbi).compareTo(Integer.valueOf(b.getGoldCoin().stripTrailingZeros().toPlainString())) >= 0) {
            addCanWithdrawMoney(b, data);
        }
        return withdrawMoney;
    }

    @RequestMapping("/record")
    @ResponseBody
    public Result record(SplitPageBean page) {
        Map<String, Object> params = new HashMap<>();
        params.put("userId", getUserId());
        List<AppCashWithdrawal> list = appCashWithdrawalService.page(params, page);
        return sucessPage(list, page.getNextPageNo());
    }
}
